from django.db import models
from django.db import connection
# Create your models here.
"""
自定义模型管理器示例
"""


class PersonDemo(models.Model):
    pass

    """
    重命名管理器名字
    """
    people = models.Manager()


class PollManager(models.Manager):
    """
        添加额外的管理器方法
    """
    def with_counts(self):
        cursor = connection.cursor()
        cursor.execute("""
            SELECT p.id, p.question, p.poll_date, COUNT(*)
            FROM ModelLearn3_opinionpoll p, ModelLearn3_response r
            WHERE p.id = r.poll_id
            GROUP BY p.id, p.question, p.poll_date
            ORDER BY p.poll_date DESC""")
        result_list = []
        for row in cursor.fetchall():
            p = self.model(id=row[0], question=row[1], poll_date=row[2])
            p.num_responses = row[3]
            result_list.append(p)
        return result_list


class OpinionPoll(models.Model):
    question = models.CharField(max_length=200)
    poll_date = models.DateField()
    objects = PollManager()


class Response(models.Model):
    poll = models.ForeignKey(OpinionPoll)
    person_name = models.CharField(max_length=50)
    response = models.TextField()


class DahlBookManager(models.Manager):
    """
    修改管理器的原始查询集示例
    """
    def get_queryset(self):
        return super(DahlBookManager, self).get_queryset().filter(author='Roald Dahl')


class Book(models.Model):
    """
    修改管理器的原始查询集示例
    """
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=50)
    objects = models.Manager()
    dahl_objects = DahlBookManager()


class PersonQuerySet(models.QuerySet):
    """
    从Manager中调用自定义的QuerySet
    """
    def authors(self):
        return self.filter(role='A')

    def editors(self):
        return self.filter(role='E')


class PersonManager(models.Manager):
    """
    从Manager中调用自定义的PersonManager
    """
    def get_queryset(self):
        return PersonQuerySet(self.model, using=self._db)

    def authors(self):
        return self.get_queryset().authors()

    def editors(self):
        return self.get_queryset().editors()


class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    role = models.CharField(max_length=1, choices=(('A', 'Author'), ('E', 'Editor')))
    people = PersonManager()







